import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:video_player/video_player.dart';

import '../index.dart';
import '../services/viewer_service.dart';

class ShareItem extends ConsumerWidget {
  final ShareEntity share;
  final bool isSquare;
  final Duration? thumbnailTime;
  final bool useSmartThumbnail;

  const ShareItem({
    super.key,
    required this.share,
    this.isSquare = false,
    this.thumbnailTime,
    this.useSmartThumbnail = true,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // 通过Provider获取作者信息，确保用户信息更新后能实时显示
    final author = ref.watch(shareAuthorProvider(share));

    // 获取当前用户
    final currentUser = ref.watch(currentUserProvider);

    // 动态生成浏览用户头像
    final viewers = ViewerService.getShareViewers(
      shareId: share.id,
      browseCount: share.browses,
      currentUserId: currentUser?.id,
    );

    return Container(
      width: double.infinity,
      height: 335.h,
      margin: EdgeInsets.only(bottom: 16.h),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(MyImages.shareBg),
          fit: BoxFit.fill,
        ),
      ),
      child: Stack(
        children: [
          // 用户信息
          Positioned(
            top: 5.h,
            left: 20.w,
            child: Row(
              children: [
                UserAvatar(
                  radius: 16.r,
                  avatarPath: author?.avatar,
                  fallbackAsset: MyImages.mark,
                ),
                SizedBox(width: 8.w),
                // 用户名
                Text(
                  author?.username ?? 'Unknown',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontFamily: 'Port',
                    fontWeight: FontWeight.w500,
                  ),
                ),

                // vip 标志
                if (author?.isVip == true && isSquare)
                  Image.asset(MyImages.vip, width: 50.w, height: 37.h),
              ],
            ),
          ),

          // 浏览量
          Positioned(
            right: 25.w,
            top: 15.h,
            child: Row(
              children: [
                // 浏览用户的头像
                if (viewers.isNotEmpty) ...[
                  SizedBox(
                    width: (viewers.length * 15 + 15).w,
                    height: 30.h,
                    child: Stack(
                      children: [
                        for (int i = 0; i < viewers.length && i < 3; i++)
                          Positioned(
                            left: (i * 15).w,
                            child: UserAvatar(
                              radius: 15.r,
                              avatarPath: viewers[i].avatar,
                            ),
                          ),
                      ],
                    ),
                  ),
                  SizedBox(width: 8.w),
                ],

                // 浏览量
                Text(
                  '+${share.browses} Watch',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12.sp,
                    fontFamily: 'Pangram',
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),

          // share图片/视频缩略图
          Positioned(
            top: 53.h,
            left: 18.w,
            child: Container(
              width: 318.15.w,
              height: 217.73.h,
              decoration: ShapeDecoration(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12.r),
                ),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12.r),
                child: share.hasVideo
                    ? LazyVideoThumbnail(
                        share: share,
                        thumbnailTime: thumbnailTime,
                        useSmartThumbnail: useSmartThumbnail,
                      )
                    : Container(
                        decoration: BoxDecoration(
                          image: share.hasImage
                              ? DecorationImage(
                                  image: AssetImage(share.image),
                                  fit: BoxFit.cover,
                                )
                              : null,
                          color: share.hasImage ? null : Colors.grey[300],
                        ),
                        child: share.hasImage
                            ? null
                            : Center(
                                child: Icon(
                                  Icons.image_not_supported,
                                  color: Colors.grey[600],
                                  size: 48.w,
                                ),
                              ),
                      ),
              ),
            ),
          ),

          // 分享描述
          Positioned(
            left: 20.w,
            bottom: 34.h,
            child: SizedBox(
              width: 289.w,
              height: 20.h,
              child: Text(
                share.description,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 15.sp,
                  fontFamily: 'inter',
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),

          // 情感标识（可选）
          if (share.emotion.isNotEmpty)
            Positioned(
              top: 60.h,
              right: 30.w,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                decoration: BoxDecoration(
                  color: Colors.black.withValues(alpha: 0.3),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Text(
                  share.emotion,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 10.sp,
                    fontFamily: 'Pangram',
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}

/// 延迟加载的视频缩略图组件
class LazyVideoThumbnail extends StatefulWidget {
  final ShareEntity share;
  final Duration? thumbnailTime;
  final bool useSmartThumbnail;

  const LazyVideoThumbnail({
    super.key,
    required this.share,
    this.thumbnailTime,
    this.useSmartThumbnail = true,
  });

  @override
  State<LazyVideoThumbnail> createState() => _LazyVideoThumbnailState();
}

class _LazyVideoThumbnailState extends State<LazyVideoThumbnail> {
  bool _shouldLoadVideo = false;
  VideoPlayerController? _controller;
  bool _isLoading = false;
  bool _hasError = false;

  @override
  void initState() {
    super.initState();
    // 延迟一小段时间再开始加载，避免列表滚动时的卡顿
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) {
        setState(() {
          _shouldLoadVideo = true;
        });
        _loadVideoThumbnail();
      }
    });
  }

  @override
  void dispose() {
    // 注意：不要释放控制器，因为它由缓存管理器管理
    super.dispose();
  }

  Future<void> _loadVideoThumbnail() async {
    if (!_shouldLoadVideo || _isLoading) return;

    setState(() {
      _isLoading = true;
      _hasError = false;
    });

    try {
      // 使用缓存管理器获取或创建控制器
      final controller = await VideoThumbnailCache().getOrCreateController(
        widget.share.video,
        thumbnailTime: widget.thumbnailTime,
        useSmartThumbnail: widget.useSmartThumbnail,
      );

      if (controller != null && mounted) {
        setState(() {
          _controller = controller;
          _isLoading = false;
        });
      } else if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('创建视频控制器失败: $e');
      if (mounted) {
        setState(() {
          _hasError = true;
          _isLoading = false;
        });
      }
    }
  }

  Widget _buildVideoOverlay() {
    return Stack(
      children: [
        // 视频播放按钮
        Center(
          child: Container(
            width: 60.w,
            height: 60.h,
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.6),
              shape: BoxShape.circle,
            ),
            child: Icon(Icons.play_arrow, color: Colors.white, size: 40.sp),
          ),
        ),
        // 视频标识
        Positioned(
          top: 8.h,
          left: 8.w,
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.7),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.videocam, color: Colors.white, size: 12.sp),
                SizedBox(width: 2.w),
                Text(
                  'VIDEO',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 8.sp,
                    fontFamily: 'Pangram',
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    // 如果还没开始加载或正在加载中，显示图片背景
    if (!_shouldLoadVideo || _isLoading || _hasError || _controller == null) {
      return Container(
        decoration: BoxDecoration(
          image: widget.share.hasImage
              ? DecorationImage(
                  image: AssetImage(widget.share.image),
                  fit: BoxFit.cover,
                )
              : null,
          color: widget.share.hasImage ? null : Colors.grey[300],
        ),
        child: Stack(
          children: [
            // 当没有图片时显示占位符
            if (!widget.share.hasImage)
              Center(
                child: Icon(
                  Icons.image_not_supported,
                  color: Colors.grey[600],
                  size: 48.w,
                ),
              ),
            _buildVideoOverlay(),
            // 加载指示器
            if (_isLoading)
              Positioned(
                bottom: 8.h,
                right: 8.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.7),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        width: 8.w,
                        height: 8.h,
                        child: CircularProgressIndicator(
                          strokeWidth: 1,
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(width: 4.w),
                      Text(
                        '加载中',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 8.sp,
                          fontFamily: 'inter',
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            // 错误提示
            if (_hasError)
              Positioned(
                bottom: 8.h,
                right: 8.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
                  decoration: BoxDecoration(
                    color: Colors.red.withValues(alpha: 0.7),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    '视频加载失败',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 8.sp,
                      fontFamily: 'inter',
                    ),
                  ),
                ),
              ),
          ],
        ),
      );
    }

    // 成功加载视频，显示视频缩略图
    return VideoThumbnailWidget(
      controller: _controller!,
      overlay: _buildVideoOverlay(),
    );
  }
}

class VideoThumbnailWidget extends StatefulWidget {
  final VideoPlayerController controller;
  final Widget overlay;

  const VideoThumbnailWidget({
    super.key,
    required this.controller,
    required this.overlay,
  });

  @override
  State<VideoThumbnailWidget> createState() => _VideoThumbnailWidgetState();
}

class _VideoThumbnailWidgetState extends State<VideoThumbnailWidget> {
  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 显示视频第一帧
        SizedBox(
          width: double.infinity,
          height: double.infinity,
          child: FittedBox(
            fit: BoxFit.cover,
            child: SizedBox(
              width: widget.controller.value.size.width,
              height: widget.controller.value.size.height,
              child: VideoPlayer(widget.controller),
            ),
          ),
        ),
        // 视频覆盖层
        widget.overlay,
      ],
    );
  }
}
